//
//  CameraScreenSaverView.m
//  CameraScreenSaver
//
//  Created by Matthew Stump on 2/1/08.
//  Copyright (c) 2008, __MyCompanyName__. All rights reserved.
//

#import "CameraScreenSaverView.h"


@implementation CameraScreenSaverView

- (id)initWithFrame:(NSRect)frame isPreview:(BOOL)isPreview {
    
    self = [super initWithFrame:frame isPreview:isPreview];
    if (self) {
        
        [self setAnimationTimeInterval:1/30.0];
        
    }
    
    [self setupCapture];
    return self;
}

- (void) setupCapture {
    
    // Create the capture view
    mCaptureView = [[QTCaptureView alloc] init];
    
    // Add the QTView to the screensaver view
    [self addSubview:mCaptureView];
    
    // Create the capture session
    mCaptureSession = [[QTCaptureSession alloc] init];
    
    // Connect inputs and outputs to the session
    BOOL success = NO;
    NSError *error;    
    
    // Find a video device
    QTCaptureDevice *device = [QTCaptureDevice defaultInputDeviceWithMediaType:QTMediaTypeVideo];
    
    if (device) {
        
        success = [device open:&error];
        
        if (!success) {
            // Handle error
        }
        
        // Add the video device to the session as device input
        mCaptureDeviceInput = [[QTCaptureDeviceInput alloc] initWithDevice:device];
        success = [mCaptureSession addInput:mCaptureDeviceInput error:&error];
        
        if (!success) {
            // Handle error
        }
        
        if (!success) {
            // Handle error
        }
                
        // Associate the capture view in the UI with the session
        [mCaptureView setCaptureSession:mCaptureSession];
        
    }
    
    // Start the capture session running
    [mCaptureSession startRunning];
    
}

- (void) setFrameSize: (NSSize) newSize {
    [super setFrameSize:newSize]; 
    [mCaptureView setFrameSize:newSize]; 
}

- (void) animateOneFrame {
    [mCaptureView setNeedsDisplay:YES];
}

- (BOOL) hasConfigureSheet {
    return NO;
}

- (NSWindow*) configureSheet {
    return nil;
}

- (void) dealloc {
    [mCaptureSession release];
    [mCaptureDeviceInput release];
    [mCaptureView release];
    [super dealloc];
}

@end
